package com.syblood.app.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.syblood.app.application.AppContext;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 应用工具类
 * Create by JiChangkong on 2022/11/02.
 */
public class AppUtil {
    private static final Handler mUiHandler = new Handler(Looper.getMainLooper());

    private final static int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private final static int CORE_POOL_SIZE = CPU_COUNT;
    private final static int MAXIMUM_POOL_SIZE = CORE_POOL_SIZE + 1;
    private final static long KEEP_ALIVE = 10L;

    private final static ThreadFactory mBackgroundThreadFactory = new ThreadFactory() {
        //AtomicInteger是一个提供原子操作的Integer类，通过线程安全的方式操作加减;
        //使用场景: AtomicInteger提供原子操作来进行Integer的使用，因此十分适合高并发情况下的使用。
        final AtomicInteger count = new AtomicInteger(1);

        @Override
        public Thread newThread(@NonNull Runnable r) {
            return new Thread(r, "Bg work thread#" + count.getAndIncrement());
        }
    };

    private static final Executor ACCOUNT_THREAD_POOL = new ThreadPoolExecutor(
            CORE_POOL_SIZE,  //核心线程数
            MAXIMUM_POOL_SIZE,  //最大线程数
            KEEP_ALIVE,  //空闲等待时间
            TimeUnit.SECONDS,  //等待时间单位
            new LinkedBlockingQueue<Runnable>(),  //阻塞队列
            mBackgroundThreadFactory);

    /*** 一小时的秒数*/
    private static final int HOUR_SECOND = 60 * 60;

    /*** 一分钟的秒数*/
    private static final int MINUTE_SECOND = 60;

    private static String mCurOrderNo = "";

    /**
     * 对外提供后台处理Executor
     *
     * @return 后台Executor
     */
    public static Executor getBackgroundExecutor() {
        return ACCOUNT_THREAD_POOL;
    }

//    @Nullable
//    public static Activity getCurTopActivity() {
//        return BaseApplication.getCurTopActivity();
//    }

    /**
     * 在后台线程中运行
     *
     * @param action Runnable
     */
    public static void runOnBgThread(Runnable action) {
        ACCOUNT_THREAD_POOL.execute(action);
    }

    /**
     * 在主线程中运行
     *
     * @param action Runnable
     */
    public static void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            mUiHandler.post(action);
        } else {
            action.run();
        }
    }

    public static void postInUiThread(Runnable action, long time) {
        mUiHandler.postDelayed(action, time);
    }

    /**
     * 延迟执行任务
     *
     * @param action
     * @param time
     */
    public static void postDelayed(Runnable action, long time) {
        new Handler().postDelayed(action, time);
    }


    /**
     * 字串是否为空
     *
     * @param charS
     * @return
     */
    public static <CharS> boolean isEmpty(CharS charS) {
        if (charS == null) {
            return true;
        }
        if (charS instanceof String) {
            return ((String) charS).isEmpty();
        } else if (charS instanceof CharSequence) {
            return ((CharSequence) charS).toString().isEmpty();
        }
        return true;
    }

    /**
     * 判断集合是否为null或者0个元素
     *
     * @param c 集合
     * @return true/false
     */
    public static boolean collectionValid(Collection c) {
        return null == c || c.isEmpty();
    }

    /**
     * 关闭软键盘
     *
     * @param view 一定要是 Edittext
     */
    public static void hideInputSoft(View view) {
//        if (getCurTopActivity() == null || view == null) {
//            return;
//        }
//        ((InputMethodManager) getCurTopActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
//                .hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    /**
     * 获取D1设备号，向D1服务器里面查询的时候最多只能有18位
     * 1# D1设备编号：D1A1016DDA000A4001
     * 3# D1设备编号：D1A1016DDA000A4003
     * 8# D1设备编号：D1A1016DDA000A4008
     *
     * @return
     */
    public static String getSerialNumber() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imei = serial;
/*        if (imei != null && imei.length() > 0) {
            switch (imei) {

                case "0123456789ABCDEF":
                   return "C10320-005";
                   return "aabbcc0320-005";
                   return "aabbcc0422-001";
                   return "aabbcc";
                   return "C10429-001";
                    return "D10505-001";
            }
            return "Z8KBBQ5DQ4RSAdzd";*//*imei;*//*
        }
        return "D10320-005";*/
        return serial;
    }

    public static String getFactoryTestFlag() {
        String result;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            result = (String) get.invoke(c, "persist.sys.mainkeys");
            if (result == null || result.isEmpty()) {
                result = "0";
            }
        } catch (Exception e) {
            result = "0";
            e.printStackTrace();
        }
        return result;
    }

    public static String getCurrentDate(String format) {
        return new SimpleDateFormat(format).format(System.currentTimeMillis());
    }

    public static String getCurrentDate() {
        return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(System.currentTimeMillis());
    }

    /**
     * 获取是当前日期的间隔天数
     */
    public static long getTwoDayInterval(String srcTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        long day = 0;
        try {
            java.util.Date curDate = formatter.parse(getCurrentDate());
            java.util.Date srcDate = formatter.parse(srcTime);
            day = (curDate.getTime() - srcDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return day;
        }
        return day;
    }

    public static String getCostTime(long startTime) {
        return "This method cost : " + (System.currentTimeMillis() - startTime) + "ms";
    }

    /**
     * 根据秒数获取时间串
     *
     * @param second (eg: 100s)
     * @return (eg : 00 : 01 : 40)
     */
    public static String getTimeStrBySecond(int second) {
        if (second <= 0) {
            return "00:00:00";
        }
        StringBuilder sb = new StringBuilder();
        int hours = second / HOUR_SECOND;
        if (hours > 0) {
            second -= hours * HOUR_SECOND;
        }
        int minutes = second / MINUTE_SECOND;
        if (minutes > 0) {
            second -= minutes * MINUTE_SECOND;
        }
        return (hours >= 10 ? (hours + "")
                : ("0" + hours) + ":" + (minutes >= 10 ? (minutes + "") : ("0" + minutes)) + ":"
                + (second >= 10 ? (second + "") : ("0" + second)));
    }

    public static void setCurOrderNo(final String orderNo) {
        mCurOrderNo = orderNo;
    }

    public static String getCurOrderNo() {
        return mCurOrderNo;
    }

    public static boolean isChineseDevice() {
        TelephonyManager tm = (TelephonyManager) AppContext.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
        String countryCode = tm.getNetworkCountryIso();
        String localeCountry = Locale.getDefault().getCountry();
        if ((!TextUtils.isEmpty(countryCode) && !"CN".equalsIgnoreCase(countryCode))
                || !"CN".equalsIgnoreCase(localeCountry)) {
            return false;
        }
        return true;
    }


    public static String getLocaleCountry() {
        String localeCountry = Locale.getDefault().getLanguage();
        return localeCountry;
    }
}
